package dice.sinanya.tools.makedata;

import com.forte.qqrobot.log.LogLevel;
import dice.sinanya.db.diceLog.InsertDiceLog;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.ArrayList;
import java.util.regex.Pattern;

public class MakeDiceLog {
    private final Log loggerForDice = LogFactory.getLog("dice");
    ArrayList<String> ignoreKey;
    ArrayList<String> hasKey;
    Pattern colorPattern = Pattern.compile("\\[[0-9]+m");
    InsertDiceLog insertDiceLog;

    public MakeDiceLog() {
        insertDiceLog = new InsertDiceLog();
        initIgnore();
        initHas();
    }

    public void makeDiceLog(String msg, LogLevel logLevel) {
        msg = makeFilter(msg);
        if (ignoreKey(msg)) {
            return;
        }
//        if (hasKey(msg)) {
//            return;
//        }
        insertDiceLog.insert(msg, logLevel);
    }

    private boolean ignoreKey(String msg) {
        for (String key : ignoreKey) {
            if (msg.contains(key)) {
                return true;
            }
        }
        return false;
    }

    private boolean hasKey(String msg) {
        boolean has = false;
        for (String key : hasKey) {
            if (msg.contains(key)) {
                has = true;
                break;
            }
        }
        return !has;
    }

    private String makeFilter(String msg) {
        return msg
                .replaceAll(colorPattern.toString(), "")
                .replace("\u001B[34m[\u001B[36mMirai\u001B[34m]\u001B[0m", "")
                .replace("\u001b\\[\\d+m", "")
                .replace("\u001B", "")
                .replace("\u001b", "")
                .replaceAll("[\\u0000-\\u001f\b]", "");
    }

    private void initHas() {
        hasKey = new ArrayList<>();
        hasKey.add("dice.sinanya.SinaNya");
        hasKey.add("dice.sinanya.tools.makedata.MakeDiceLog");
    }

    private void initIgnore() {
        ignoreKey = new ArrayList<>();
        ignoreKey.add("OnlinePush.RespPush");
        ignoreKey.add("Heartbeat.Alive");
        ignoreKey.add("mirai不支持的API");
        ignoreKey.add("已被阻止");
        ignoreKey.add("MessageSvc");
    }
}
